#include "usart.h"
#include "main.h"
#include "log.h"
#include "crsf.h"
#include "sbus.h"
#include "gpio.h"
#include "config.h"
#include "ppm.h"


uint8_t send_sbus_flag = 0;

void setup(void)
{
	LOG_DEBUG("Start");
    
#ifdef MODE_CRSF_TO_SBUS
	uart1_init();
	uart2_init();

	crc8_init();
#endif
    
#ifdef MODE_PPM_TO_CRSF
	uart2_init();
	crc8_init();
    ppm_init();
#endif
}

void loop(void)
{
#ifdef MODE_CRSF_TO_SBUS
    CRSF_handle_uart_in();
	
	if(send_sbus_flag)
	{
        send_sbus_flag = 0;
        
		sbus_build_packet(crsf_channels,CRSF_get_state());			
		uart1_write(sbus_frame,25);
	}
#endif
    
#ifdef MODE_PPM_TO_CRSF
    
#endif
}

/**
 * @brief call by systick interrupu per one milli second
 * 
 */
void app_timer_callback(void)
{
	static int count = 0;
    static int count2=0;

	count++;
	if(count==500)
	{
		if(CRSF_get_state() == CRSF_DISCONNECT)
		{
			led_off();
		}
	}
	if(count==1000)
	{		
		led_on();
		count = 0;
	}
    
    count2++;
    if(count2 >= SBUS_INTERVAL)
    {
        count2 = 0;
        send_sbus_flag = 1;
    }
}
